package com.lego.jbv;

import lejos.nxt.*;
import lejos.nxt.comm.*;

import java.io.*;


public class BTController extends Thread {
    private static String connected = "Connected";
    private static String waiting = "Waiting...";
    private static String closing = "Closing...";

    private static BTConnection btc;
    private static DataInputStream dis;
    private static DataOutputStream dos;
    
    private int minMotorPower = 0;
    private int maxMotorPower = 100;
    private boolean gotoLight = false;
    
    public BTController(){
    	btc = null;
    }
    
    public void run() 
    {
    	LCD.drawString(waiting,0,0);

        btc = Bluetooth.waitForConnection();
        
        LCD.clear();
        LCD.drawString(connected,0,0);	

        dis = btc.openDataInputStream();
        dos = btc.openDataOutputStream();
              
        read();
    }
    
    public static void send(int minInput, int maxInput)
    {
    	if(btc != null)
    	{
	    	try
	    	{
				dos.writeInt(minInput);
				dos.writeInt(maxInput);
				dos.flush();
			}
	    	
	    	catch (IOException e) 
	    	{
	    	}
    	}
    }
    
    private void read()
    {
    	int y = 0;
    	LCD.clear();
		LCD.drawString("Reading.",0,3);	
    	while (true)
        {
    		try
            {
            	if(btc.available() > 0)
            	{
            		minMotorPower = dis.readInt();
            		maxMotorPower = dis.readInt();
            		gotoLight = dis.readBoolean();
            		LCD.drawInt(minMotorPower, 5, 0, 6);
            		LCD.drawInt(maxMotorPower, 5, 7, 6);
            	}
            	sleep(2000);
            }
            catch (Exception e)
            {
            	LCD.drawString("Read fail", 0, 0);
            }
        }
    }
		   
    public void stop() 
    {
        LCD.clear();
        LCD.drawString(closing,0,0);
    	try 
    	{
    	    dis.close();
            dos.close();
            Thread.sleep(100); // wait for data to drain
            btc.close();    	
    	}
        catch (Exception e)
        {
        	LCD.drawString("Stop fail", 0, 0);
        }
        try {Thread.sleep(1000);}catch (Exception e){}
        System.exit(0);
    }
    
    public synchronized int getMinMotorPower()
    {
    	return minMotorPower;
    }
    
    public synchronized int getMaxMotorPower()
    {
    	return maxMotorPower;
    }
    
    public synchronized boolean getGotoLight()
    {
    	return gotoLight;
    }
}